package servlet;

import  java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import javax.servlet.*;
import  javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;
import entity.Goods;
@WebServlet("/goodsServlet")
public class GoodsServlet extends HttpServlet{
    private static final long serialVersionUID=1L;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        Connection con=null;
        Statement st=null;
        //结果集
        ResultSet rs=null;
        ArrayList<Goods> allGoods =null;
        //加载驱动
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
        try{
            con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test?characterEncoding=utf-8","root","mrt286933605");
            st=con.createStatement();
            request.setCharacterEncoding("utf-8");
            st.executeUpdate("insert into goods values(null,'"+request.getParameter("gname")+"',"+request.getParameter("gprice")+")");
            rs=st.executeQuery("select * from goods");
            allGoods=new ArrayList<Goods>();
            while(rs.next()){
                Goods g=new Goods();
                g.setId(rs.getInt(1));
                g.setGname(rs.getString(2));
                g.setGprice(rs.getDouble(3));
                allGoods.add(g);
            }
            rs.close();
            st.close();
        }catch (SQLException e){
            e.printStackTrace();
        }
        request.setAttribute("allGoods",allGoods);
        RequestDispatcher dis=request.getRequestDispatcher("showGoods.jsp");
        dis.forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
